//
//  HMNetworkTools.swift
//  02-Swift网络封装
//
//  Created by Apple on 2017/7/11.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    case get
    case post
}

//  网络请求工具类
class HMNetworkTools: AFHTTPSessionManager {

    //  单例的全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools;
    }()
    //  get/post通用网络请求
    fileprivate func request(type: RequestType, urlStr: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        if type == .get {
            get(urlStr, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        } else {
            post(urlStr, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        }
    }
    
}

//  MARK:   --首页相关接口
extension HMNetworkTools {

    
    /// 微博首页数据
    ///
    /// - Parameters:
    ///   - accessToken: 令牌
    ///   - callBack: 闭包回调
    func requestStatuses(accessToken: String, max_id: Int64 = 0, since_id: Int64 = 0, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        //  请求参数
        let params: [String : Any] = [
            "access_token": accessToken,
            "max_id": max_id,
            "since_id": since_id
        ]
        print(urlStr + "?access_token=" + accessToken)
        //  执行网络请求
        request(type: .get, urlStr: urlStr, params: params, callBack: callBack)
    }
    
}

//  MARK:   --发微博相关接口
extension HMNetworkTools {
    
    /// 发微博
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - status: 微博内容
    ///   - pic: 微博图片
    func sendWeibo(access_token: String, status: String, pic: UIImage? = nil, callBack: @escaping (Any?, Error?) -> ()) {
        //  地址
        let urlStr = "https://api.weibo.com/2/statuses/share.json"
        //  请求参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        
        if pic == nil {
            
            request(type: .post, urlStr: urlStr, params: params, callBack: callBack)
            
        } else {
        
            let imageData = UIImageJPEGRepresentation(pic!, 0.5)!
            post(urlStr, parameters: params, constructingBodyWith: { (formData) in
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            }, progress: nil, success: { (_, response) in
                callBack(response, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
            
        }
        
    }
}

//  MARK:   --OAuth相关接口
extension HMNetworkTools {
    
    /// 获取用户信息
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - uid: 用户id
    ///   - callBack: 闭包回调
    func requestUserInfo(access_token: String, uid: Int64, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/users/show.json"
        //  请求参数
        let params: [String: Any] = [
            "access_token": access_token,
            "uid": uid
        ]
        //  执行网络请求
        request(type: .get, urlStr: urlStr, params: params, callBack: callBack)
    }
    
    /// 根据code获取accesstoken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - callBack: 回调
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        //  请求参数
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_Uri
        ]
        //  执行网络请求
        request(type: .post, urlStr: urlStr, params: params, callBack: callBack)
    }
}

